import React, { useState, useEffect } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { AtList, AtListItem, AtInput, AtMessage } from 'taro-ui'
import { request } from '@/utils'
import mscanPng from '../../assets/images/mscan.png'
import { ALLTABS } from '@/config'

import './index.less'

const ScanQRCode = () => {
  const [name, setName] = useState('')
  const [oilSupplierId, setOilSupplierId] = useState('')
  const [oilSupplierName, setOilSupplierName] = useState('')
  const [role, setRole] = useState('')
  const [applyNum, setApplyNum] = useState('')
  Taro.getStorage({
    key: 'userInfo',
    success(res) {
      const { user } = JSON.parse(res.data)
      setName(user.name)
      setOilSupplierId(user.oilSupplierId)
      setOilSupplierName(user.oilSupplierName)
      setRole(user.role)
    }
  })
  const handleClick = () => {
    if(!applyNum) {
      Taro.atMessage({message: '请先输入油量', type: 'error'})
      return
    }
    Taro.scanCode({
     async success(res) {
        console.log(res);
        Taro.showLoading({mask: true})
        const { error } = await request({url: 'hkshihua/motorcade/oil/pay',method: 'POST',header: {'content-type': 'application/json'}, data: JSON.stringify({userPayCode: res.result,oilSupplierId, applyNum})})
        console.log(error);
        if(error) return
        Taro.atMessage({message: '操作成功！', type: 'success'})
      },
      error() {
        Taro.atMessage({message: '无效的二维码', type: 'error'})
      }
    })
  }
  const handleChange = (e) => {
    setApplyNum(e)
  }
  const handleTClick = (num) => {
    setApplyNum(num)
  }
  useDidShow(() => {
    Taro.getCurrentPages()[0].getTabBar().setData({
      selected: 0
    })
  })
  useEffect(() => {
    Taro.getCurrentPages()[0].getTabBar().setData({
      list: ALLTABS[role]
    })
  }, [role])
  return <View className='scan'>
    <AtMessage />
    <AtList>
      <AtListItem title={oilSupplierName} extraText={name} />
    </AtList>
    <View className='content'>
      <View className='title'>扫码加油</View>
      <View>
        <AtInput cursor={-1} title='加油量：' name='applyNum' type='number' value={applyNum} placeholder='请输入油量' onChange={handleChange} />
        <View className='tip'>
          <View onClick={() => { handleTClick(100)}}>100升</View>
          <View onClick={() => { handleTClick(200)}}>200升</View>
          <View onClick={() => { handleTClick(300)}}>300升</View>
        </View>
        <View className='footer'>
          <Image src={mscanPng} onClick={handleClick} />
        </View>
      </View>
    </View>
  </View>
}

export default ScanQRCode
